package com.zl.boke.config.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author zhanglei2
 * @since 2020/1/12 20:01
 */
@Aspect//切面注解
@Component//扫描组件
public class LogAspect {
    //获取日志记录
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //获取切面
    @Pointcut("execution(* com.zl.boke.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        String url = request.getRequestURI();
        //获取类方法需要通过织入点来获取
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] ages = joinPoint.getArgs();
        ResultLog resultLog = new ResultLog(ip, url, classMethod, ages);
        System.out.println("--------doAfter---------");
        logger.info("Request : {}", resultLog);
    }
    @After("log()")
    public void doAfter() {
        logger.info("--------doAfter---------");
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("Result :  {}", result);
    }

    public class ResultLog {
        private String ip;//地址
        private String url;//路径
        private String classMethod;//类方法
        private Object[] args;//参数

        public ResultLog(String ip, String url, String classMethod, Object[] args) {
            this.ip = ip;
            this.url = url;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "ResultLog{" +
                    "ip='" + ip + '\'' +
                    ", url='" + url + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
